<template>
  <el-dialog
    :model-value="modelValue"
    @update:model-value="$emit('update:modelValue', $event)"
    title="数据对比详情"
    width="90%"
    top="5vh"
    destroy-on-close
  >
    <div v-if="!dataLoaded" class="loading-container">
      <el-skeleton :rows="15" animated />
    </div>
    <div v-else>
      <el-descriptions :column="3" border>
        <el-descriptions-item label="任务名称">{{ currentLog.task_name }}</el-descriptions-item>
        <el-descriptions-item label="批次号">{{ currentLog.batch_no }}</el-descriptions-item>
        <el-descriptions-item label="执行状态">
          <el-tag :type="getStatusType(currentLog.status)">{{ getStatusText(currentLog.status) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="执行信息">{{ currentLog.message }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDateTime(currentLog.created_at) }}</el-descriptions-item>
      </el-descriptions>
      
      <!-- 数据对比表格组件 -->
      <comparison-table
        :log-id="currentLog._id"
        v-model:loading="contrastLoading"
        :page-size="100"
        ref="comparisonTableRef"
      />
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getTaskLogDetail } from '@/api/data-sync';
import { getStatusText, getStatusType, formatDateTime } from './utils';
import ComparisonTable from './ComparisonTable.vue';

// 定义组件接收的属性
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  logId: {
    type: String,
    default: ''
  }
});

// 定义组件触发的事件
const emit = defineEmits(['update:modelValue']);

// 当前日志详情
const currentLog = ref<any>({});
const dataLoaded = ref(false);

// 对比数据加载状态
const contrastLoading = ref(false);
const comparisonTableRef = ref();

// 加载详情数据
const loadLogDetail = async (id: string) => {
  if (!id) return;
  
  try {
    dataLoaded.value = false;
    
    // 加载详情
    const detailRes: any = await getTaskLogDetail(id);
    if (detailRes.code === 200 && detailRes.data) {
      currentLog.value = detailRes.data;
    } else {
      ElMessage.error('获取日志详情失败');
    }
  } catch (error) {
    console.error('获取详情出错:', error);
    ElMessage.error('获取详情出错');
  } finally {
    dataLoaded.value = true;
  }
};

// 监听对话框状态变化
watch(() => props.modelValue, (newVal) => {
  if (!newVal) {
    // 关闭对话框时清空数据
    currentLog.value = {};
  }
});

// 监听logId变化加载详情
watch(() => props.logId, (newVal) => {
  if (newVal && props.modelValue) {
    loadLogDetail(newVal);
  }
}, { immediate: true });
</script>

<style lang="scss" scoped>
.loading-container {
  min-height: 300px;
  padding: 20px;
}
</style>